import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";

export default defineConfig(({ command, mode }) => {
  // 根据当前工作目录中的 `mode` 加载 .env 文件
  const env = loadEnv(mode, process.cwd(), "");

  // 生成时间戳
  const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, -5);
  const buildTime = new Date()
    .toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    })
    .replace(/[/:]/g, "")
    .replace(/\s/g, "");

  return {
    define: {
      __URL__: JSON.stringify(env.VITE_API_URL),
      __ENVIRONMENT__: JSON.stringify(env.VITE_APP_ENVIRONMENT),
      __ISNETWORKING__: JSON.stringify(env.VITE_APP_ISNETWORKING),
      __NAME__: JSON.stringify(env.VITE_APP_NAME),
      __VERSION__: JSON.stringify(env.VITE_APP_VERSION),
      __GLOBAL_LOADING__: env.VITE_GLOBAL_LOADING === "YES",
      __REDIRECT__:
        env.VITE_REDIRECT === "NO" ? false : JSON.stringify(env.VITE_REDIRECT),
      __DINGTALK__: env.VITE_DINGTALK === "YES",
      __DINGTALK_REDIRECT__:
        env.VITE_DINGTALK_REDIRECT === "NO"
          ? false
          : JSON.stringify(env.VITE_DINGTALK_REDIRECT),

      __DINGTALK_BROWSER__: env.VITE_DINGTALK_BROWSER === "YES",
      __DINGTALK_BROWSER_REDIRECT__:
        env.VITE_DINGTALK_BROWSER_REDIRECT === "NO"
          ? false
          : JSON.stringify(env.VITE_DINGTALK_BROWSER_REDIRECT),
      __DINGTALK_BROWSER_CLIENT__: JSON.stringify(
        env.VITE_DINGTALK_BROWSER_CLIENT
      ),

      __WECHAT__: env.VITE_WECHAT === "YES",
      __WECHAT_REDIRECT__:
        env.VITE_WECHAT_REDIRECT === "NO"
          ? false
          : JSON.stringify(env.VITE_WECHAT_REDIRECT),
      __WECHAT_CLIENT__: JSON.stringify(env.VITE_WECHAT_CLIENT),
    },
    plugins: [vue()],
    //解决“vite use `--host` to expose”
    base: "./",
    server: {
      host: "0.0.0.0", //ip地址
      port: 8080, // 设置服务启动端口号
      open: true, // 设置服务启动时是否自动打开浏览器
      //   proxy: {
      //     '/base_url': {
      //         // target: 'http://localhost:9000',
      //         target: 'http://10.31.0.92:8847',
      //         secure: false,
      //         // 是否允许跨域
      //         changeOrigin: true,
      //         rewrite: path => path.replace(/^\/base_url/, '')
      //     }
      // }
    },

    build: {
      minify: false,
      // 进行压缩计算
      brotliSize: false,
      // 设置大文件报警阈值（单位：kb）
      chunkSizeWarningLimit: 500,
      // 启用 gzip 压缩报告
      reportCompressedSize: true,
      // 构建时清空输出目录
      emptyOutDir: true,
      //指定输出路径
      // assetsDir: "./dist",
      // 指定输出文件路径 - 直接输出到 version 目录
      outDir: env.VITE_DIST_PATH,
      // 代码压缩配置
      terserOptions: {
        // 生产环境移除console
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
      // chunkSizeWarningLimit: 1500,大文件报警阈值设置,不建议使用
      rollupOptions: {
        output: {
          //静态资源分类打包 - 添加时间戳
          chunkFileNames: `static/js/[name]-[hash]-${buildTime}.js`,
          entryFileNames: `static/js/[name]-[hash]-${buildTime}.js`,
          // assetFileNames: "static/[ext]/[name]-[hash].[ext]",
          assetFileNames(assetInfo) {
            // 判断后缀分别放到不用的文件夹中 - 添加时间戳
            if (assetInfo.name.endsWith(".css")) {
              return `static/css/[name]-[hash]-${buildTime}.[ext]`;
            }
            if (
              ["png", "jpg", "svg", "PNG"].some((ext) =>
                assetInfo.name.endsWith(ext)
              )
            ) {
              return `static/img/[name]-[hash]-${buildTime}.[ext]`;
            }
            if (
              ["ttf", "woff", "woff2"].some((ext) =>
                assetInfo.name.endsWith(ext)
              )
            ) {
              return `static/fonts/[name]-[hash]-${buildTime}.[ext]`;
            }
            return `static/css/[name]-[hash]-${buildTime}.[ext]`;
          },
          manualChunks(id) {
            // 优化分包策略，避免单文件过大 - 将 element-plus 拆分成更小的包
            if (id.includes("node_modules")) {
              // 提取包名和组件路径
              const moduleName = id
                .split("node_modules/")[1]
                ?.split("/")[0]
                ?.toString();

              // Element Plus 图标库
              if (id.includes("@element-plus/icons-vue")) {
                return "element-icons-vendor";
              }

              // Element Plus 组件细粒度拆分
              if (id.includes("element-plus/es/components")) {
                const componentMatch = id.match(/components\/([^/]+)/);
                if (componentMatch) {
                  const componentName = componentMatch[1];

                  // 基础组件
                  if (
                    ["button", "input", "textarea", "icon"].some((name) =>
                      componentName.includes(name)
                    )
                  ) {
                    return "element-basic-vendor";
                  }
                  // 表单组件
                  if (
                    ["form", "select", "checkbox", "radio", "switch"].some(
                      (name) => componentName.includes(name)
                    )
                  ) {
                    return "element-form-vendor";
                  }
                  // 表格组件
                  if (
                    ["table", "pagination"].some((name) =>
                      componentName.includes(name)
                    )
                  ) {
                    return "element-table-vendor";
                  }
                  // 消息提示组件
                  if (
                    ["message", "notification", "message-box"].some((name) =>
                      componentName.includes(name)
                    )
                  ) {
                    return "element-message-vendor";
                  }
                  // 弹窗组件
                  if (
                    ["dialog", "drawer", "popover", "tooltip"].some((name) =>
                      componentName.includes(name)
                    )
                  ) {
                    return "element-popup-vendor";
                  }
                  // 布局组件
                  if (
                    ["container", "layout", "aside", "header", "main"].some(
                      (name) => componentName.includes(name)
                    )
                  ) {
                    return "element-layout-vendor";
                  }
                  // 数据展示组件
                  if (
                    ["card", "tag", "badge", "progress", "circle"].some(
                      (name) => componentName.includes(name)
                    )
                  ) {
                    return "element-display-vendor";
                  }
                  // 导航组件
                  if (
                    ["menu", "breadcrumb", "tabs", "steps"].some((name) =>
                      componentName.includes(name)
                    )
                  ) {
                    return "element-navigation-vendor";
                  }
                  // 反馈组件
                  if (
                    ["loading", "skeleton", "empty", "result"].some((name) =>
                      componentName.includes(name)
                    )
                  ) {
                    return "element-feedback-vendor";
                  }
                  // 日期时间组件
                  if (
                    ["date-picker", "time-picker", "calendar"].some((name) =>
                      componentName.includes(name)
                    )
                  ) {
                    return "element-datetime-vendor";
                  }
                  // 上传组件
                  if (
                    ["upload", "image"].some((name) =>
                      componentName.includes(name)
                    )
                  ) {
                    return "element-upload-vendor";
                  }
                  // 其他杂项组件
                  return "element-misc-vendor";
                }
              }

              // Element Plus 核心工具（先匹配核心，再匹配其他）
              if (id.includes("element-plus") && !id.includes("/components/")) {
                return "element-plus-core-vendor";
              }

              // 其他 Element Plus 相关文件（但不在 components 目录）
              if (id.includes("element-plus")) {
                return "element-plus-misc-vendor";
              }

              // 钉钉 SDK
              if (id.includes("dingtalk")) {
                return "dingtalk-vendor";
              }

              // Vue Router
              if (id.includes("vue-router")) {
                return "vue-router-vendor";
              }

              // Pinia
              if (id.includes("pinia")) {
                return "pinia-vendor";
              }

              // Vue 核心库（排除 router 和 pinia）
              if (
                id.includes("vue") &&
                !id.includes("vue-router") &&
                !id.includes("pinia") &&
                !id.includes("vue-demi")
              ) {
                return "vue-core-vendor";
              }

              // Axios 网络请求库
              if (id.includes("axios")) {
                return "axios-vendor";
              }

              // Lodash 工具库
              if (id.includes("lodash")) {
                return "lodash-vendor";
              }

              // dayjs 日期库
              if (id.includes("dayjs")) {
                return "dayjs-vendor";
              }

              // VueUse 工具库
              if (id.includes("@vueuse")) {
                return "vueuse-vendor";
              }

              // async-validator 验证库
              if (id.includes("async-validator")) {
                return "async-validator-vendor";
              }

              // Popper.js 相关
              if (id.includes("@popperjs") || id.includes("popper")) {
                return "popper-vendor";
              }

              // Floating UI
              if (id.includes("@floating-ui") || id.includes("floating-ui")) {
                return "floating-ui-vendor";
              }

              // 其他第三方库按包名分包
              return moduleName || "vendor";
            }

            // 处理业务代码按路由分包（可选）
            if (id.includes("src/")) {
              // 如果某个页面特别大，可以按需分包
              return null; // 使用默认分包策略
            }
          },
        },
      },
    },

    resolve: {
      //别名配置，引用src路径下的东西可以通过@如：import Layout from '@/layout/index.vue'
      alias: [
        {
          find: "@",
          replacement: resolve(__dirname, "src"),
        },
        {
          find: "@api",
          replacement: resolve(__dirname, "src/axios/api"),
        },
        {
          find: "@store",
          replacement: resolve(__dirname, "src/store"),
        },
        {
          find: "@page",
          replacement: resolve(__dirname, "src/page"),
        },
        {
          find: "@utils",
          replacement: resolve(__dirname, "src/utils"),
        },
        {
          find: "@axios",
          replacement: resolve(__dirname, "src/axios"),
        },
        {
          find: "@assets",
          replacement: resolve(__dirname, "src/assets"),
        },
        {
          find: "@cpmt",
          replacement: resolve(__dirname, "src/components"),
        },
      ],
    },
  };
});
